import 'package:flutter_admin/api/odoo/dms_userqualifications_odoo_api.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/models/odoo/dms_userqualifications.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';
import '../../../generated/l10n.dart';

class DmsUserqualificationsEdit extends StatefulWidget {
  DmsUserqualificationsEdit({this.dmsUserqualifications});

  final DmsUserqualifications? dmsUserqualifications;

  @override
  _DmsUserqualificationsEditState createState() =>
      _DmsUserqualificationsEditState();
}

class _DmsUserqualificationsEditState extends State<DmsUserqualificationsEdit> {
  late DmsUserqualifications dmsUserqualifications;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  DateFormat format = DateFormat('yyyy-MM-dd');

  List<SelectOptionVO> deptIdList = [];
  List<SelectOptionVO> userIdList = [];
  List<SelectOptionVO> certificatetypeList = [];
  @override
  void initState() {
    super.initState();
    this.isAdd = widget.dmsUserqualifications == null;
    this.dmsUserqualifications =
        widget.dmsUserqualifications ?? DmsUserqualifications();
    _loadSelectVO();
  }

  _loadSelectVO() async {
    deptIdList = await DynamicDataApi.getModelSelect(
      model: "hr.department",
      name: "complete_name",
    );
    if (isAdd == false) {
      userIdList = await DynamicDataApi.getUserSelect(
          val: int.parse(dmsUserqualifications.departmentId!));
    } else {
      var deparment =
          StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
      dmsUserqualifications.departmentId = deparment[0].toString();
      userIdList = await DynamicDataApi.getUserSelect(
          val: int.parse(dmsUserqualifications.departmentId!));
    }
    certificatetypeList = await DynamicDataApi.getDictList("certificatetype");
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 300,
            label: '证书编号',
            value: dmsUserqualifications.certificateno,
            onSaved: (v) {
              dmsUserqualifications.certificateno = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            width: 280,
            label: '培训日期',
            value: dmsUserqualifications.traindate,
            lastDate: isNotBlank(dmsUserqualifications.Issuingdate)
                ? format.parse(dmsUserqualifications.Issuingdate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              dmsUserqualifications.traindate = v;
              setState(() {});
            },
            onSaved: (v) {
              dmsUserqualifications.traindate = v;
            },
          ),
          CryInput(
            width: 300,
            label: '证书名称',
            value: dmsUserqualifications.certificatename,
            onSaved: (v) {
              dmsUserqualifications.certificatename = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 300,
            label: '发证单位',
            value: dmsUserqualifications.Issuingcompany,
            onSaved: (v) {
              dmsUserqualifications.Issuingcompany = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            width: 300,
            label: '证书类别',
            dataList: certificatetypeList,
            value: dmsUserqualifications.certificatetypeId,
            onSaved: (v) {
              dmsUserqualifications.certificatetypeId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            width: 280,
            label: '发证日期',
            value: dmsUserqualifications.Issuingdate,
            firstDate: isNotBlank(dmsUserqualifications.traindate)
                ? format.parse(dmsUserqualifications.traindate!)
                : null,
            lastDate: isNotBlank(dmsUserqualifications.expirydate)
                ? format.parse(dmsUserqualifications.expirydate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              dmsUserqualifications.Issuingdate = v;
              setState(() {});
            },
            onSaved: (v) {
              dmsUserqualifications.Issuingdate = v;
            },
          ),
          CrySelect(
            width: 300,
            label: '部门',
            dataList: deptIdList,
            value: dmsUserqualifications.departmentId,
            onSaved: (v) {
              dmsUserqualifications.departmentId = v;
            },
            onChange: (v) async {
              if (dmsUserqualifications.departmentId != v) {
                formKey.currentState!.save();
                dmsUserqualifications.departmentId = v;
                dmsUserqualifications.holderId = null;
                userIdList = [];
                try {
                  userIdList =
                      await DynamicDataApi.getUserSelect(val: int.parse(v));
                } catch (e) {
                  userIdList = [];
                }
                setState(() {});
              }
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            width: 280,
            label: '有效截止日期',
            value: dmsUserqualifications.expirydate,
            firstDate: isNotBlank(dmsUserqualifications.Issuingdate)
                ? format.parse(dmsUserqualifications.Issuingdate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              dmsUserqualifications.expirydate = v;
              setState(() {});
            },
            onSaved: (v) {
              dmsUserqualifications.expirydate = v;
            },
          ),
          CrySelect(
            width: 300,
            label: '证书持有人',
            dataList: userIdList,
            value: dmsUserqualifications.holderId,
            onSaved: (v) {
              dmsUserqualifications.holderId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 300,
            label: '备注',
            value: dmsUserqualifications.remark,
            onSaved: (v) {
              dmsUserqualifications.remark = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            DmsUserqualificationsOdooApi.saveOrUpdate(
                    dmsUserqualifications.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
